//
//  EmoticonViewController.swift
//  02-表情
//
//  Created by 张宏芝 on 15/9/11.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit

private let EmoticonCellID = "EmoticonCellID"

// 表情键盘控制器---系统默认的高度是216
class EmoticonViewController: UIViewController {
    
    /// 选中表情的闭包回调
    var selectedEmoticonCallBack:(emoticon:Emoticon)->()
    init(selectedEmoticon:(emoticon:Emoticon)->()){
        
        selectedEmoticonCallBack = selectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    MARK:---监听方法
    @objc private func clickItem(item:UIBarButtonItem){
        print(item.tag)
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        加载表情数据
        setupUI()
    }

//    MARK:---设置界面
    private func setupUI(){
//        1.添加控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
//        2.自动布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["tb":toolBar,"cv":collectionView]
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
//        3.准备控件
        prepareToolbar()
        preparCollectionView()
    }
    

//    准备工具栏
    private func prepareToolbar(){
        
        toolBar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
//        通常通过tag区分toolbar上的按钮
        var index = 0
        for p in viewModel.packages{
            items.append(UIBarButtonItem(title: p.group_name_cn, style: UIBarButtonItemStyle.Plain, target: nil, action: "clickItem:"))
            
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    //    准备collectionView
    private func preparCollectionView(){
        collectionView.backgroundColor = UIColor.whiteColor()
//        注册cell
      collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellID)
//        指定数据源 & 代理
      collectionView.dataSource = self
        collectionView.delegate = self
    }
    
//    MARK:---懒加载控件
//    工具栏
    private lazy var toolBar = UIToolbar()
//    collectionView
    private lazy var collectionView  = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLaoyout())
//    表情模型的视图模型
    private lazy var viewModel = EmoticonViewModel.sharedViewModel
}

// 表情键盘的布局
private class EmoticonLaoyout:UICollectionViewFlowLayout{
//    准备布局,第一次使用的时候会调用
    private override func prepareLayout() {
        super.prepareLayout()
        
        print(collectionView)
        
        let width = collectionView!.bounds.width / 7
        let margin = ((collectionView?.bounds.height)! - 3*width)*0.5
        itemSize = CGSize(width: width, height: width)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0

        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}

//  MARK:UICollectionViewDataSource
extension EmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
//    分组数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count
    }
//    每(section)表情包,包含的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmoticonCell
//        表情包得索引
        cell.emoticon = viewModel.emoticon(indexPath)
        return cell
    }
    
//    选中cell的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        执行闭包回调
        selectedEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
//        添加最近表情的符号
        viewModel.favorite(indexPath)
//       刷新 collectionView 第0组
//        用户体验不好：会闪动/表情会变化位置
         collectionView.reloadSections(NSIndexSet(index: 0))

    }
}

// 表情cell
private class EmoticonCell:UICollectionViewCell {
    
//    设置模型
    var emoticon:Emoticon?{
        didSet{
//            1.图片
            print(emoticon?.imagePath)
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
//            2.emoji
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
//            3.删除按钮
            if emoticon!.isRemove{
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
//        CGRectInset:返回相同中心点得矩形
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
//        设置字体
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK:懒加载控件
    private lazy var emoticonButton:UIButton = UIButton()
}






























